package kxfang.com.common.core.activity;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;

import java.util.ArrayList;
import java.util.List;

/**
 * activity管理类
 */
public class ActivityStackManage {

    private static List<Activity> activityList = new ArrayList<>();

    public static ActivityLife getActivityLife() {
        return new ActivityLife();
    }

    private static class ActivityLife implements Application.ActivityLifecycleCallbacks {

        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            activityList.add(activity);
        }

        @Override
        public void onActivityStarted(Activity activity) {

        }

        @Override
        public void onActivityResumed(Activity activity) {

        }

        @Override
        public void onActivityPaused(Activity activity) {

        }

        @Override
        public void onActivityStopped(Activity activity) {

        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

        }

        @Override
        public void onActivityDestroyed(Activity activity) {
            activityList.remove(activity);
        }
    }

    /**
     * 退出除activity外的界面
     * @param activity
     */
    public static void popAll(Activity activity) {
        if (activityList.size() == 0) {
            return;
        }
        try {
            for (Activity act : activityList) {
                if(act==activity){
                    continue;
                }
                act.finish();
            }
        } catch (Exception e) {

        }
    }

    /**
     * 退出该activity
     * @param activity
     */
    public static void pop(Activity activity){
        if (activityList.size() == 0) {
            return;
        }
        try {
            for (Activity act : activityList) {
                if(act==activity){
                    act.finish();
                    break;
                }
            }
        } catch (Exception e) {

        }
    }

    /**
     * 退出所有的activity
     */
    public static void popAll() {
        if (activityList.size() == 0) {
            return;
        }
        try {
            for (Activity act : activityList) {
                act.finish();
            }
        } catch (Exception e) {

        }
    }
}
